<?php

namespace App\Modules\CodeDesigner\Memento;

// 负责创建一个备忘录memento，用以记录当前时刻它的内部状态
class Originator
{
    private $state;

    public function __construct(string $state)
    {
        $this->state = $state;
        echo "我的初始化状态：" . $state;
    }

    public function doSomething(): void
    {
        echo "Originator: I'm doing something important.\n";
        $this->state = $this->generateRandomString(30);
        echo "Originator: and my state has changed to: {$this->state}\n";
    }

    public function generateRandomString($length = 10): string
    {
        return substr(
            str_shuffle(
                str_repeat(
                    $x = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
                    ceil($length / strlen($x))
                )
            )
            , 1, $length);
    }

    /**
     * 保存状态
     * @return MementoInterface
     */
    public function save(): MementoInterface
    {
        return new MementoImpl($this->state);
    }

    public function restore(MementoInterface $memento): void
    {
        $this->state = $memento->getState();
        echo "Originator: My state has changed to: {$this->state}\n";
    }
}